﻿#region copyright
// Halcyone - Silverlight Application Framework
// Copyright (C) 2009 - 2010 Alexey Zakharov (B&Z LLC)
// 
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.Text;

namespace Witcraft.Halcyone.ServiceModel
{
    using System.IO;
    using System.Runtime.Serialization.Json;

    /// <summary>
    /// 
    /// </summary>
    public static class ObjectExtensions
    {
        public static string ToUriCompatibleString(this object value)
        {
            string result;

            if (IsPrimitive(value))
            {
                return PrimitiveToUriCompatibleString(value);
            }

            using (var memmoryStream = new MemoryStream())
            {
                var jsonSerilizer = new DataContractJsonSerializer(value.GetType());

                jsonSerilizer.WriteObject(memmoryStream, value);

                memmoryStream.Position = 0;

                using (var reader = new StreamReader(memmoryStream))
                {
                    result = reader.ReadToEnd();
                }
                    
            }

            return result;
        }

        private static bool IsPrimitive(object value)
        {
            Type type = value.GetType();
            return type.IsPrimitive || type == typeof (string) || type == typeof (DateTime) || type == typeof (Decimal);
        }

        private static string PrimitiveToUriCompatibleString(Object value)
        {
            if (value is DateTime)
            {
                return ((DateTime) value).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);
            }

            return string.Format(CultureInfo.InvariantCulture,"{0}",value);
        }
    }
}